package com.gxa.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gxa.domain.entity.PromotionType;
import com.gxa.service.PromotionTypeService;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.dao.DataIntegrityViolationException;
import java.util.List;

@RestController
@RequestMapping("/api/promotion-types")
@Tag(name = "活动类型管理", description = "活动类型信息管理相关接口")
@CrossOrigin(origins = "*")
public class PromotionTypeController {
    // 注入PromotionTypeService
    @Autowired
    private PromotionTypeService promotionTypeService;

    // 获取所有活动类型
    @GetMapping
    public List<PromotionType> list() {
        return promotionTypeService.list();
    }

    // 根据id获取活动类型
    @GetMapping("/{id}")
    public PromotionType get(@PathVariable Integer id) {
        return promotionTypeService.getById(id);
    }

    // 添加活动类型
    @PostMapping
    public boolean add(@RequestBody PromotionType promotionType) {
        return promotionTypeService.save(promotionType);
    }

    // 修改活动类型
    @PutMapping
    public boolean update(@RequestBody PromotionType promotionType) {
        return promotionTypeService.updateById(promotionType);
    }

    // 根据id删除活动类型
    @DeleteMapping("/{id}")
    public Object delete(@PathVariable Integer id) {
        try {
            boolean result = promotionTypeService.removeById(id);
            return result;
        } catch (DataIntegrityViolationException e) {
            Throwable cause = e.getCause();
            if (cause != null && cause.getMessage() != null && cause.getMessage().contains("a foreign key constraint fails")) {
                return "该活动类型已被活动引用，无法删除，请先删除相关活动！";
            }
            throw e;
        }
    }
    //    public boolean delete(@PathVariable Integer id) {
    //        return promotionTypeService.removeById(id);
    //    }

}
